#!/usr/bin/env python3
"""
Simple Frontend Server - Serve the HTML frontend using Python's built-in HTTP server
"""

import os
import sys
from pathlib import Path
from http.server import HTTPServer, SimpleHTTPRequestHandler
import webbrowser
import threading
import time

class CORSRequestHandler(SimpleHTTPRequestHandler):
    """HTTP request handler with CORS support"""
    
    def __init__(self, *args, **kwargs):
        # Set the directory to serve files from
        super().__init__(*args, directory=str(Path(__file__).parent / "frontend"), **kwargs)
    
    def end_headers(self):
        """Add CORS headers to all responses"""
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', '*')
        super().end_headers()
    
    def do_OPTIONS(self):
        """Handle preflight requests"""
        self.send_response(200)
        self.end_headers()
    
    def log_message(self, format, *args):
        """Override to reduce log noise"""
        pass

def open_browser():
    """Open browser after a short delay"""
    time.sleep(2)
    webbrowser.open('http://localhost:8000')

def main():
    """Main function to start the frontend server"""
    print("=" * 70)
    print("🌐 Event Contract Platform - Simple Frontend Server")
    print("=" * 70)
    print(f"📁 Serving files from: {Path(__file__).parent / 'frontend'}")
    print("🔗 Frontend URL: http://localhost:8000")
    print("🔗 Backend WebSocket: ws://localhost:8768")
    print("💾 localStorage support: ✅ Enabled")
    print()
    print("📖 Instructions:")
    print("1. Make sure the backend server is running:")
    print("   python demo_server.py")
    print()
    print("2. The browser will open automatically, or go to:")
    print("   http://localhost:8000")
    print()
    print("3. Create a user account and start trading!")
    print("=" * 70)
    print()
    
    # Check if frontend directory exists
    frontend_dir = Path(__file__).parent / "frontend"
    if not frontend_dir.exists():
        print("❌ Error: frontend directory not found!")
        return
    
    if not (frontend_dir / "index.html").exists():
        print("❌ Error: index.html not found in frontend directory!")
        return
    
    # Start the server
    server_address = ('localhost', 8000)
    httpd = HTTPServer(server_address, CORSRequestHandler)
    
    # Open browser in a separate thread
    threading.Thread(target=open_browser, daemon=True).start()
    
    print("🚀 Server starting on http://localhost:8000")
    print("🛑 Press Ctrl+C to stop the server")
    print()
    
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("\n🛑 Stopping server...")
        httpd.shutdown()
        print("✅ Server stopped")

if __name__ == "__main__":
    main()
